package com.yenlien.traceyun.admin.interceptor;

import com.yenlien.traceyun.common.crypt.TokenUtil;
import com.yenlien.traceyun.common.exception.TokenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-09
 * @description:
 **/
public class TokenInterceptor implements HandlerInterceptor {

    private String[] exceptUrls = {"/user/login", "/error"};

    @Autowired
    private TokenProperties tokenProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过地址集拦截
        String url = request.getRequestURI();
        for (String item : exceptUrls) {
            if (url.startsWith(item)) {
                return true;
            }
        }
        //通过注解拦截，如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (!passToken.required()) {
                return true;
            }
        }
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {
            token = request.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                throw new TokenException("未登录");
            }
        }
        TokenUtil.veryToken(token, tokenProperties.getSecret());
        return true;
    }
}
